<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :auto-upload="true"
      :on-change="onChange"
      :on-remove="onRemove"
      :on-preview="onPreview"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :http-request="httpRequest"
      :class="{ hidden: fileList.length === uploadMaxNum }"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <!-- <el-progress
      v-if="showPercent"
      :percentage="percentage"
      style="width: 180px"
    ></el-progress> -->
    <el-dialog title="预览图片" :visible.sync="showDialog" width="width">
      <img :src="imgUrl" width="50%" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { upImageApi } from "@/api/subject/subject.js";
export default {
  name: "ImageUpload",
  props: {
    uploadMaxNum: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      imgUrl: "",
      showDialog: false,
      fileList: [], //图片预览地址
      currentFileUid: "",
      showPercent: false,
      percentage: 0,
    };
  },
  methods: {
    // 图片上传步骤
    // 1.上传组件改变事件
    onChange(file, fileList) {
      // 组件自带change事件,file是文件信息，fileList是文件列表
      // 将最新的图片使用map遍历插入其中、
      console.log(file);
      this.fileList = fileList.map((item) => item);
    },
    // 2.图片预览事件
    // 将弹框打开，图片地址赋值给预览图片地址
    onPreview(file) {
      this.showDialog = true;
      this.imgUrl = file.url;
    },
    // 3.上传前进行大小格式校验
    beforeUpload(file) {
      // 这里一般做 体积的判断 类型的校验
      // file是原生的文件信息
      // console.log("beforeUpload", file);
      const maxSize = 1024 * 1024 * 200; //最大5m
      if (file.size > maxSize) {
        this.$message.warning("体积不允许超过5m");
        return false;
      }
      const typeArr = [
        "image/jpg",
        "image/jpeg",
        "image/gif",
        "image/png",
        "image/mp4",
      ];
      if (!typeArr.includes(file.type)) {
        this.$message.warning("格式不正确");
        return false;
      }
      // 进度条显示
      this.currentFileUid = file.uid;
      this.showPercent = true;
      this.percentage = 0;
      return true;
    },
    // 4.自定义上传事件
    async httpRequest({ file }) {
      let fd = new FormData();
      fd.append("file", file);
      // 调用上传图片接口上传图片
      let a = await upImageApi(fd);
    },
    // 删除图片
    onRemove(file, fileList) {
      this.fileList = this.fileList.filter((item) => item.uid !== file.uid);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .hidden {
  div.el-upload {
    display: none;
  }
}
</style>